package com.example.personal.aiagent.user.login;

import com.alibaba.fastjson.JSON;
import com.example.personal.aiagent.user.model.vo.LoginRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义前后端分离认证 Filter
 */
@Slf4j
public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
        throws AuthenticationException {
        // 1.判断是否是 post 方式请求
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        // 2.判断是否是 json 格式请求类型
        if (request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
            // 3.从 json 数据中获取用户输入用户名和密码进行认证 {"uname":"xxx","password":"xxx","remember-me":true}
            try {
                LoginRequest userInfo = JSON.parseObject(request.getInputStream(), LoginRequest.class);
                String username = userInfo.getUsername();
                String password = userInfo.getPassword();
                boolean rememberValue = userInfo.isRememberMe();
                if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
                    throw new AuthenticationServiceException("param missed ");
                }
                request.setAttribute(AbstractRememberMeServices.DEFAULT_PARAMETER, rememberValue);
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username,
                    password);
                setDetails(request, authRequest);
                return this.getAuthenticationManager().authenticate(authRequest);
            } catch (IOException ex) {
                log.error("parse error", ex);
            }
        }
        return super.attemptAuthentication(request, response);
    }
}
